package com.dudu.access;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import com.dudu.bean.DialResultBean;
import com.dudu.bean.ResponseSendVoiceBean;
import com.dudu.service.ILogService;
import com.dudu.service.impl.LogService;
import com.dudu.utils.DateUtils;
import com.dudu.utils.DictionaryUtils;
import com.dudu.utils.HttpRequest;

import core.CoreService;

/**
 * 天亿通道
 * 
 * @author gaoxs
 * 
 */
public class TianYiUtil {

    private static String ServerUrl = DictionaryUtils.getValueByTypeAndKey("tianYi", "url");
    private static String token = DictionaryUtils.getValueByTypeAndKey("tianYi", "token");
    private static String token_qingdao = DictionaryUtils.getValueByTypeAndKey("tianYi", "token_qingdao"); // 青岛项目专用token
    private static ILogService logService = new LogService();

    public static void main(String[] agr) throws Exception {
    }

    /**
     * 天亿语音通知
     * 
     * @param called
     *            被叫号码
     * @param mediaName
     *            语音文件名称，播放多个文件用英文逗号隔开。与mediaTxt不能同时为空。当不为空时mediaTxt属性失效
     * @param mediaTxt
     *            文本内容，文本中汉字要求utf8编码，默认值为空。当mediaName为空才有效
     * @param displayNum
     *            来电显示的号码，根据平台侧显号规则控制
     * @param respUrl
     *            外呼通知状态通知回调地址
     * @param userData
     * @param 是否青岛项目请求
     *            ，青岛项目适用单独的token
     * @return
     */
    public static ResponseSendVoiceBean VoiceNotice(String called, String mediaName, String mediaTxt, String displayNum, String respUrl, String userData, boolean isQingDao) {
	ResponseSendVoiceBean responseSendVoice = new ResponseSendVoiceBean();
	long begin = Calendar.getInstance().getTimeInMillis();
	JSONObject object = new JSONObject();
	String responsedata = "";
	String result = "-1";
	String sessionid = "";
	String desc = "";
	try {
	    if (isQingDao) {
		object.put("token", token_qingdao);
	    } else {
		object.put("token", token);
	    }
	    object.put("To", called);// 被叫号码，被叫为座机时需要添加区号
	    object.put("mediaName", mediaName);// 语音文件名称，播放多个文件用英文逗号隔开
	    object.put("mediaTxt", mediaTxt);// 文本内容，文本中汉字要求utf8编码
	    // 来电显示的号码
	    object.put("displayNum", displayNum.trim());// 来电显示的号码
	    object.put("respUrl", respUrl);// 外呼通知状态通知回调地址
	    object.put("userData", userData);// 第三方私有数据，可在外呼通知状态通知中获取此参数
	    // object.put("txtSpeed", "0");//文本转语音后的发音速度，取值范围：-500至500，
	    // object.put("txtVolume", "100");//文本转语音后的音量大小，取值范围：-500至500
	    // object.put("txtPitch", "0");//文本转语音后的音调，取值范围：-500至500
	    String Myurl = ServerUrl + "Calls/LandingCalls";
	    responsedata = HttpRequest.postData(Myurl, object.toString());
	    CoreService.log.info("VoiceNotice req:" + object.toString() + "response:" + responsedata);
	    if (StringUtils.isNotBlank(responsedata)) {
		JSONObject response = JSONObject.fromObject(responsedata);
		// 前导音为文本是使用%C 前导音为语音文件时使用%V吗？
		result = response.optString("statusCode");
		if (result.equals("00000")) {
		    result = "0";
		    sessionid = response.optString("callSid");
		    desc = "OK";
		} else {
		    desc = response.optString("ExceptionMessage");
		}
	    } else {
		responsedata = "";
		desc = "接口未响应";
	    }

	} catch (Exception e) {
	    responsedata="异常"+ e.getMessage();
	}
	long end = Calendar.getInstance().getTimeInMillis();
	double time = Double.valueOf((end - begin)) / 1000;
	logService.logIms(time, "TianYiNotice", "【" + object.toString() + "】", "【" + responsedata + "】", result, DateUtils.getCurrentTime(), "TianYi", called);
	responseSendVoice.setResult(result);
	responseSendVoice.setSessionid(sessionid);
	responseSendVoice.setDesc(desc);
	return responseSendVoice;
    }

    /**
     * 上传文件 1、先把mp3格式转成wav 2、把文件转成二进制流
     * 
     * @param fileName
     * @param completeFileName
     * @return
     */
    public static ResponseSendVoiceBean UploadFile(String fileName, String completeFileName, boolean isQingDao) {
	ResponseSendVoiceBean bean = new ResponseSendVoiceBean();
	// 记录发起的开始时间
	Long begin = Calendar.getInstance().getTimeInMillis();
	try {
	    // 判断是否为mp3文件
	    if (completeFileName.endsWith("mp3")) {
		CoreService.log.info("开始上传文件中，文件为mp3格式，需要转成wav");
		// 生成wav存放地址
		String completeFileName2 = completeFileName.substring(0, completeFileName.lastIndexOf(".")) + ".wav";
		// 把mp3格式转化为wav格式
		boolean res = ConvertAudio.convert2(completeFileName, completeFileName2);
		if (res) {
		    CoreService.log.info("开始上传文件中，文件为mp3格式，需要转成wav,转换成功" + fileName);
		    completeFileName = completeFileName2;
		} else {
		    CoreService.log.info("开始上传文件中，文件为mp3格式，需要转成wav,转换失败" + fileName);

		    bean.setResult("-1");
		    bean.setFileName("");
		    return bean;
		}
	    }
	    String url = ServerUrl + "Calls/MediaFileBCDUpload";
	    JSONObject params = new JSONObject();
	    if (isQingDao) {
		params.put("token", token_qingdao);
	    } else {
		params.put("token", token);
	    }
	    // params.put("token", token);
	    params.put("filename", fileName);
	    String req = url + "?" + params.toString();

	    String responsedata = HttpRequest.sendHttpPostRequest(url, params, completeFileName);
	    CoreService.log.info("UploadFile req:" + req + "---response:" + responsedata);
	    String result = "-1";
	    if (StringUtils.isNotBlank(responsedata)) {
		JSONObject response = JSONObject.fromObject(responsedata);
		result = response.optString("statusCode");
		if (StringUtils.isNotBlank(result) && result.equals("00000")) {
		    result = "0";
		} else {
		    result = "-1";
		}
	    } else {
		responsedata = "";
	    }

	    Long end = Calendar.getInstance().getTimeInMillis();
	    Double during = Double.valueOf((end - begin)) / 1000;
	    logService.logIms(during, "UploadFile", "上传文件-tianyi-" + fileName, "【" + responsedata + "】", result + "", DateUtils.getCurrentTime(), "TianYi", "");
	    bean.setResult(result);
	    bean.setFileName("");
	    return bean;
	} catch (Exception e) {
	    e.printStackTrace();
	    CoreService.log.error("文件：" + fileName + "上传失败");
	}
	bean.setResult("999999");
	bean.setFileName("");
	return bean;
    }

    /**
     * 闪信
     * 
     * @param called
     * @comments 此接口不稳定，暂不开放
     */
    public static void QuickSMS(String called) {
	ResponseSendVoiceBean responseSendVoice = new ResponseSendVoiceBean();
	long begin = Calendar.getInstance().getTimeInMillis();
	JSONObject object = new JSONObject();
	String responsedata = "";
	String result = "";
	String sessionid = "";
	try {
	    object.put("token", "246FD99CAFD80F4495F38C66A3FA70AD");
	    // object.put("token", token);
	    object.put("Tel", called);// 被叫号码，被叫为座机时需要添加区号
	    String Myurl = ServerUrl + "LandingCalls";
	    responsedata = HttpRequest.postData("http://SMSPolicy.tioeycinda.cn/api/QuickSMS/SendSMS", object.toString());
	    // System.out.println(responsedata);
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }

    /**
     * 天亿双向外呼（点击拨号、两方通话）
     * 
     * @param token
     *            默认值07F8899BB9BE87706F4893CC8EEEBAC0
     * @param caller
     *            主叫
     * @param called
     *            被叫
     * @param customerSerNum
     * @param fromSerNum
     * @param ticketUrl
     * @param needRecord
     *            是否录音：0表示不录音；1表示录音；默认值0（天亿暂不支持录音）
     * @param display_mode
     *            1：显示主叫号码、0：显示平台配置号码
     * @param connectTime
     *            连接时长
     * @return
     */
    public static DialResultBean dial(String caller, String called, String displayNum, String ticketUrl, String needRecord, String display_mode, String connectTime) {
	DialResultBean resultBean = new DialResultBean();
	JSONObject object = new JSONObject();
	String responsedata = "";
	String result = "-1";
	String sessionid = "";
	long begin = 0;
	long end = 0;
	String Myurl = "";
	String calledDisplay;
	if (StringUtils.isNotBlank(display_mode) && display_mode.equals("1")) {
	    if (caller.indexOf("14") == 0 || caller.indexOf("17") == 0 || caller.indexOf("8614") == 0 || caller.indexOf("8617") == 0) {
		calledDisplay = displayNum.trim(); // 被叫侧显示的号码
	    } else {
		calledDisplay = caller; // 被叫侧显示的号码
	    }

	} else {
	    calledDisplay = displayNum.trim(); // 被叫侧显示的号码
	}
	try {
	    /**
	     * 拼接请求参数
	     */
	    object.put("token", token); // token
	    object.put("callerTel", caller); // 主叫号码
	    object.put("calledTel", called); // 被叫号码
	    object.put("dispalyCallerTel", displayNum); // 主叫显示
	    object.put("dispalyCalledTel", calledDisplay); // 被叫显示：显示主叫号码
	    object.put("connectTime", connectTime); // 连接时长
	    object.put("respUrl", ticketUrl); // 外呼通知状态通知回调地址,平台将向该Url地址发送呼叫结果通知
	    Myurl = ServerUrl + "TowWayCall/Calling";
	    begin = Calendar.getInstance().getTimeInMillis();
	    responsedata = HttpRequest.postData(Myurl, object.toString());
	    CoreService.log.info("dial req:" + object.toString() + "---response:" + responsedata);
	    end = Calendar.getInstance().getTimeInMillis();
	    if (StringUtils.isNotBlank(responsedata)) {
		JSONObject response = JSONObject.fromObject(responsedata);
		sessionid = response.optString("CdrId");
		if (StringUtils.isNotBlank(sessionid)) {
		    result = "0";
		} else {
		    result = "-1";
		    String exceptionType = response.optString("ExceptionType");
		    String exceptionMessage = response.optString("ExceptionMessage");
		    responsedata = exceptionType + "：" + exceptionMessage;
		}
	    } else {
		responsedata = "请求返回为空";
		result = "-1";
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	    responsedata = "请求异常：" + e.getMessage();
	    result = "-1";
	}
	double time = Double.valueOf((end - begin)) / 1000;
	logService.logIms(time, "Dial_tianyi", "【" + Myurl + object.toString() + "】", "【" + responsedata + "】", result, DateUtils.getCurrentTime(), "TianYi", caller);
	resultBean.setDisplayNbr(displayNum);
	resultBean.setResult(result);
	resultBean.setSessionId(sessionid);
	resultBean.setDesc(responsedata);
	return resultBean;
    }

    /**
     * IVR 外呼
     * 
     * @param called
     *            被叫号码
     * @param displayNum
     *            来电显示的号码，根据平台侧显号规则控制
     * @param mediaName
     *            语音文件名称，播放多个文件用英文逗号隔开。与mediaTxt不能同时为空。当不为空时mediaTxt属性失效
     * @param mediaTxt
     *            文本内容，文本中汉字要求utf8编码，默认值为空。当mediaName为空才有效
     * @param respUrl
     *            外呼通知状态通知回调地址
     * @return
     */
    public static ResponseSendVoiceBean IvrDial(String called, String displayNum, String mediaName, String mediaTxt, String respUrl, String number) {
	ResponseSendVoiceBean responseSendVoice = new ResponseSendVoiceBean();
	long begin = Calendar.getInstance().getTimeInMillis();
	JSONObject object = new JSONObject();
	String responsedata = "";
	String result = "-1";
	String sessionid = "";
	try {
	    object.put("token", token);
	    object.put("To", called);// 被叫号码，被叫为座机时需要添加区号
	    object.put("mediaName", mediaName);// 语音文件名称，播放多个文件用英文逗号隔开
	    object.put("mediaTxt", mediaTxt);// 文本内容，文本中汉字要求utf8编码
	    // 来电显示的号码
	    object.put("displayNum", displayNum.trim());// 来电显示的号码
	    object.put("respUrl", respUrl);// 外呼通知状态通知回调地址
	    object.put("userData", "");// 第三方私有数据，可在外呼通知状态通知中获取此参数
	    List sublist = new ArrayList();
	    JSONObject subobject = null;
	    for (int i = 0; i <= 9; i++) {
		subobject = new JSONObject();
		subobject.put("Keyboard", i);
		subobject.put("ActionMode", "0");
		subobject.put("TransferTo", "");
		sublist.add(subobject);
	    }
	    subobject = new JSONObject();
	    subobject.put("Keyboard", "*");
	    subobject.put("ActionMode", "1");
	    subobject.put("TransferTo", "");
	    sublist.add(subobject);
	    subobject = new JSONObject();
	    subobject.put("Keyboard", "#");
	    subobject.put("ActionMode", "2");
	    subobject.put("TransferTo", number);
	    sublist.add(subobject);
	    object.put("keyboard", sublist);// 按键操作数组
	    String Myurl = ServerUrl + "Calls/LandingCalls";
	    responsedata = HttpRequest.postData(Myurl, object.toString());
	    CoreService.log.info("IvrDial req:" + object.toString() + "---response:" + responsedata);
	    if (StringUtils.isNotBlank(responsedata)) {
		JSONObject response = JSONObject.fromObject(responsedata);
		// 前导音为文本是使用%C 前导音为语音文件时使用%V吗？
		result = response.optString("statusCode");
		if (result.equals("00000")) {
		    result = "0";
		    sessionid = response.optString("callSid");
		} else {
		    result = "-1";
		    String exceptionType = response.optString("ExceptionType");
		    String exceptionMessage = response.optString("ExceptionMessage");
		    responsedata = exceptionType + "：" + exceptionMessage;
		}
	    } else {
		responsedata = "";
		result = "-1";
	    }
	} catch (Exception e) {
	    responsedata="异常"+ e.getMessage();
	}
	long end = Calendar.getInstance().getTimeInMillis();
	double time = Double.valueOf((end - begin)) / 1000;
	logService.logIms(time, "TianYiIVR", "【" + object.toString() + "】", "【" + responsedata + "】", result, DateUtils.getCurrentTime(), "TianYi", called);
	responseSendVoice.setResult(result);
	responseSendVoice.setSessionid(sessionid);
	responseSendVoice.setDesc(responsedata);
	return responseSendVoice;
    }

    /**
     * 天亿两方挂断接口
     * 
     * @param sessionId
     * @return
     */
    public static JSONObject dialStop(String sessionId) {
	JSONObject object = new JSONObject();
	object.put("token", token); // token
	object.put("CdrId", sessionId); // 主叫号码
	String url = ServerUrl + "TowWayCall/DropCall";
	long begin = Calendar.getInstance().getTimeInMillis();
	long end = 0;
	String responsedata = "";
	String result = "-1";
	try {
	    responsedata = HttpRequest.postData(url, object.toString());
	    CoreService.log.info("dialStop req:" + object.toString() + "---response:" + responsedata);
	    end = Calendar.getInstance().getTimeInMillis();
	    if (StringUtils.isNotBlank(responsedata)) {
		JSONObject response = JSONObject.fromObject(responsedata);
		String status = response.getString("statusCode");
		if ("00000".equals(status))
		    result = "0";
	    }
	} catch (Exception err) {
	    CoreService.log.error("调用天亿两方结束接口异常", err);
	} finally {
	    double time = Double.valueOf((end - begin)) / 1000;
	    logService.logIms(time, "DailStop", "【" + object.toString() + "】", "【" + responsedata + "】", result, DateUtils.getCurrentTime(), "TianYi", "");
	}
	JSONObject rc = new JSONObject();
	rc.put("result", result);
	return rc;
    }

}
